/*
 * Copyright (c) 2025 Industrial Software Feature Database
 */
package com.comac.ins.isfd.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.comac.ins.common.core.constant.CommonConstant;
import com.comac.ins.common.core.exception.base.BaseException;
import com.comac.ins.common.core.utils.MapstructUtils;
import com.comac.ins.common.excel.utils.ExcelUtil;
import com.comac.ins.common.mybatis.core.page.PageQuery;
import com.comac.ins.common.mybatis.core.page.TableDataInfo;
import com.comac.ins.isfd.constant.enums.IsfdMetadataTableNameEnum;
import com.comac.ins.isfd.domain.IsfdLayupMetalCaseMeta;
import com.comac.ins.isfd.domain.IsfdMetalMaterial;
import com.comac.ins.isfd.domain.bo.IsfdLayupMetalCaseMetaBo;
import com.comac.ins.isfd.domain.bo.query.IsfdLayupMetalCaseMetaQueryBo;
import com.comac.ins.isfd.domain.vo.IsfdLayupMetalCaseMetaVo;
import com.comac.ins.isfd.mapper.IsfdLayupMetalCaseMetaMapper;
import com.comac.ins.isfd.mapper.IsfdMetalMaterialMapper;
import com.comac.ins.isfd.service.IIsfdLayupMetalCaseMetaService;
import com.comac.ins.isfd.service.IIsfdMetadataImportService;
import com.comac.ins.system.service.ISysDictDataService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.Collection;
import java.util.List;

/**
 * 【请填写功能名称】Service业务层处理
 *
 * @author Lion Li
 * @date 2024-08-02
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class IsfdLayupMetalCaseMetaServiceImpl implements IIsfdLayupMetalCaseMetaService, IIsfdMetadataImportService {

    @Autowired
    private final IsfdLayupMetalCaseMetaMapper baseMapper;

    @Autowired
    private final IsfdMetalMaterialMapper metalMaterialMapper;

    @Autowired
    private final ISysDictDataService sysDictDataService;

    /**
     * 查询【请填写功能名称】
     *
     * @param id 主键
     * @return 【请填写功能名称】
     */
    @Override
    public IsfdLayupMetalCaseMetaVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询【请填写功能名称】列表
     *
     * @param bo        查询条件
     * @return 【请填写功能名称】分页列表
     */
    @Override
    public TableDataInfo<IsfdLayupMetalCaseMetaVo> queryPageList(IsfdLayupMetalCaseMetaQueryBo bo) {
        PageQuery pageQuery = new PageQuery();
        pageQuery.setPageNum(bo.getPageNum());
        pageQuery.setPageSize(bo.getPageSize());
        LambdaQueryWrapper<IsfdLayupMetalCaseMeta> lqw = buildQueryWrapper(bo);
        Page<IsfdLayupMetalCaseMetaVo> result = baseMapper.queryPageList(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的【请填写功能名称】列表
     *
     * @param bo 查询条件
     * @return 【请填写功能名称】列表
     */
    @Override
    public List<IsfdLayupMetalCaseMetaVo> queryList(IsfdLayupMetalCaseMetaQueryBo bo) {
        LambdaQueryWrapper<IsfdLayupMetalCaseMeta> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<IsfdLayupMetalCaseMeta> buildQueryWrapper(IsfdLayupMetalCaseMetaQueryBo bo) {
        LambdaQueryWrapper<IsfdLayupMetalCaseMeta> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getAttributeCode()), IsfdLayupMetalCaseMeta::getAttributeCode, bo.getAttributeCode());
        lqw.eq(bo.getThickness() != null, IsfdLayupMetalCaseMeta::getThickness, bo.getThickness());
        lqw.eq(StringUtils.isNotBlank(bo.getPshellNumber()), IsfdLayupMetalCaseMeta::getPshellNumber, bo.getPshellNumber());
        lqw.eq(StringUtils.isNotBlank(bo.getMaterialCode()), IsfdLayupMetalCaseMeta::getMaterialCode, bo.getMaterialCode());
        lqw.apply(StringUtils.isNotBlank(bo.getSectionNumber()),"LEFT(pshell_number, 2) = {0}", bo.getSectionNumber()); // 前两位匹配部段号
        return lqw;
    }

    /**
     * 新增【请填写功能名称】
     *
     * @param bo 【请填写功能名称】
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(IsfdLayupMetalCaseMetaBo bo) {
        validEntityBeforeSave(bo);
        IsfdLayupMetalCaseMeta add = MapstructUtils.convert(bo, IsfdLayupMetalCaseMeta.class);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改【请填写功能名称】
     *
     * @param bo 【请填写功能名称】
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(IsfdLayupMetalCaseMetaBo bo) {
        validEntityBeforeSave(bo);
        IsfdLayupMetalCaseMeta update = MapstructUtils.convert(bo, IsfdLayupMetalCaseMeta.class);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(IsfdLayupMetalCaseMetaBo entity) {
        if (entity == null) {
            throw new BaseException("实体不能为空");
        }

        String sectionNumber = entity.getSectionNumber();

        if (sectionNumber == null || sectionNumber.length() != 2) {
            throw new BaseException("部段号(sectionNumber)不能为空且必须是2位");
        }

        // 校验材料代码
        checkMaterialCode(entity);

        // 校验PSHELL编号
        checkPshellNumber(entity);

        // 校验属性代码
        checkAttributeCode(entity);

        // 校验唯一
        Long count = baseMapper.selectCount(
            new LambdaQueryWrapper<IsfdLayupMetalCaseMeta>()
                .eq(IsfdLayupMetalCaseMeta::getThickness, entity.getThickness())
                .eq(IsfdLayupMetalCaseMeta::getMaterialCode, entity.getMaterialCode())
                .apply("LEFT(pshell_number, 2) = {0}", sectionNumber) // 前两位匹配部段号
                .ne(entity.getId() != null, IsfdLayupMetalCaseMeta::getId, entity.getId()) // 更新时排除自身
        );
        if (count > 0) {
            throw new BaseException("已存在相同属性金属壳单元");
        }

    }

    // 校验材料代码是否存在
    private void checkMaterialCode(IsfdLayupMetalCaseMetaBo entity) {
        String materialCode = entity.getMaterialCode();
        if (StringUtils.isBlank(materialCode)) {
            throw new BaseException("材料代码不能为空");
        }

        // 查询材料表
        IsfdMetalMaterial metalMaterial = metalMaterialMapper.selectOne(
            new LambdaQueryWrapper<IsfdMetalMaterial>()
                .eq(IsfdMetalMaterial::getMaterialNumber, materialCode)
        );

        if (metalMaterial == null) {
            throw new BaseException("材料代码不存在，请确认后重试！");
        }

        // todo: 把属性放到位置
        entity.setExx(metalMaterial.getE());
        entity.setEyy(metalMaterial.getE());
        entity.setGxy(metalMaterial.getE()/metalMaterial.getNu());
    }

    // 校验PSHELL编号
    private void checkPshellNumber(IsfdLayupMetalCaseMetaBo entity) {
        String sectionNumber = entity.getSectionNumber();
        if (sectionNumber == null || sectionNumber.length() != 2) {
            throw new BaseException("部段号(sectionNumber)不能为空且必须是2位");
        }

        try {
            String sectionName = sysDictDataService.selectDictLabel(CommonConstant.PARAMETRIC_MODELING_SECTIONS, entity.getSectionNumber());
            if (StringUtils.isBlank(sectionName)) {
                throw new BaseException("当前部段不存在，请检查部段号：" + sectionNumber);
            }
        } catch (Exception e) {
            throw new BaseException("当前部段不存在，请检查部段号：" + sectionNumber);
        }

        String pshellNumber = generateNextPshellNumber(sectionNumber, entity.getId());
        entity.setPshellNumber(pshellNumber);
    }

    public String generateNextPshellNumber(String sectionNumber, Long id) {
        if (sectionNumber == null || sectionNumber.length() != 2) {
            throw new BaseException("部段号(sectionNumber)不能为空且必须是2位");
        }

        // 更新场景
        if (id != null) {
            // 查询数据库里的老 pshell_number
            IsfdLayupMetalCaseMeta oldMetalCase = baseMapper.selectById(id);
            String oldPshell = oldMetalCase.getPshellNumber();
            if (oldPshell != null && oldPshell.length() >= 2) {
                String oldSection = oldPshell.substring(0, 2);
                // 如果部段号没变，直接返回老 pshell_number，不用重新生成
                if (oldSection.equals(sectionNumber)) {
                    return oldPshell;
                }
            }
        }

        // 查询数据库中同一组的最大 pshell_number，排除自己（更新时用）
        String maxPshell = baseMapper.selectMaxPshellBySection(sectionNumber, id);

        // 如果该组还没有数据，从 sectionNumber + "000001" 开始
        if (maxPshell == null) {
            return sectionNumber + "000001";
        }

        // 自增
        long maxNum = Long.parseLong(maxPshell);
        long nextNum = maxNum + 1;

        // 格式化为 8 位，不足补 0
        String nextPshell = String.format("%08d", nextNum);

        // 判断长度是否超过8位
        if (nextPshell.length() > 8) {
            throw new BaseException("生成的PSHELL编号超过最大长度 8 位，请检查部段号或数据");
        }

        return nextPshell;
    }

    // 检查属性代码
    private void checkAttributeCode(IsfdLayupMetalCaseMetaBo entity) {
        // todo: 拼接方式
        String attributeCode;
        String materialCode = entity.getMaterialCode();
        Double thickness = entity.getThickness();
        attributeCode = materialCode + "-" + doubleToStringNoDot(thickness);
        entity.setAttributeCode(attributeCode);
    }

    private static String doubleToStringNoDot(double value) {
        BigDecimal bd = new BigDecimal(Double.toString(value));
        bd = bd.stripTrailingZeros(); // 去掉末尾无用的0
        String plain = bd.toPlainString(); // 转字符串，防科学计数法
        return plain.replace(".", ""); // 去掉小数点
    }


    /**
     * 校验并批量删除【请填写功能名称】信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public IsfdLayupMetalCaseMetaVo queryByLayCode(String layCode) {
        return baseMapper.selectVoOne(new LambdaQueryWrapper<IsfdLayupMetalCaseMeta>().eq(IsfdLayupMetalCaseMeta::getAttributeCode, layCode));
    }

    @Override
    public String selectByTableName() {
        return IsfdMetadataTableNameEnum.ISFD_LAYUP_METAL_CASE_META.getValue();
    }

    @Override
    public Long excelImport(File excelImportFile, String metadataManagementId) {
        long successCount = 0L;
        try (InputStream is = new FileInputStream(excelImportFile)) {
            List<IsfdLayupMetalCaseMetaVo> targetVo = ExcelUtil.importExcel(is, IsfdLayupMetalCaseMetaVo.class);
            for (IsfdLayupMetalCaseMetaVo vo : targetVo) {
                IsfdLayupMetalCaseMetaBo bo = MapstructUtils.convert(vo, IsfdLayupMetalCaseMetaBo.class);

                try{
                    bo.setMetadataManagementId(metadataManagementId);
                    insertByBo(bo);
                    successCount++;
                } catch (Exception e) {
                    log.error("金属壳单元属性数据导入失败", e);
                }
            }

        } catch (Exception e) {
            log.error("sheet文件转换为实体类失败", e);
            throw new BaseException("sheet文件转换为实体类失败");
        }

        return successCount;
    }
}
